﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using LightLog.Model.Config;
using LightLog.IService;
using LightLog.Service;
using FreeSqlExtensions;
using LightLog.Entity;
using LightLog.Framework;
using LightLog.Framework.Extensions;
using LightLog.Model.Input;
using Mapster;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using JwtHelper = LightLog.Service.JwtHelper;


namespace LightLog.Service
{
    public class LogInfoService : BaseService, ILogInfoService
    {
        private readonly IFreeSql _fsql;

        public LogInfoService(IFreeSql fsql)
        {
            _fsql = fsql;
        }

        public async Task<bool> LoggingAsync(SeriLogInput input)
        {
            //mapster 忽略空值
            TypeAdapterConfig<SeriLogInput, Entity.LogInfo>.NewConfig().IgnoreNullValues(true);
            var logModel = input.Properties?.Input?.Adapt<Entity.LogInfo>();
            if (logModel == null)
            {
                logModel = new LogInfo();
                logModel.ExceptionInfo = input.RenderedMessage;
            }
            logModel.LogLevel = input.Level;
            logModel.ClientSystem =string.IsNullOrEmpty(logModel.ClientSystem)? HttpHelper.GetUserAgent().ToMaxLengthString(500): logModel.ClientSystem;
            logModel.IP = HttpHelper.GetTrueUserIP().ToMaxLengthString(50);
            logModel.CreateTime = input.Timestamp.AddHours(8);//utc时间转北京时间是8个小时

            return await _fsql.Insert(logModel).ExecuteAffrowsAsync() > 0;
        }

    }
}
